//
//  MPCButton+SDWebImage.m
//  Pods
//
//  Created by jiaxuzhou on 2017/7/26.
//
//

#import "MPCButton+SDWebImage.h"

#if MPT_USE_SDWebImageSwitch

/// 保存SDWebImage下载队列key
static NSString *SDWebImageLoadOperationKey = @"SDWebImageLoadOperationKey";

#endif

@implementation MPCButton (SDWebImage)

#if MPT_USE_SDWebImageSwitch

- (void)mptsd_cancelCurrentImageLoad
{
    [self sd_cancelImageLoadOperationWithKey:SDWebImageLoadOperationKey];
}

- (UIImage *)sd_getCatcheMemoryImageWithImageURL:(NSURL *)imgUrl options:(MPWebImageOptions)options
{
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
    NSString *key = [manager cacheKeyForURL:imgUrl];
    
    if (key)
    {
        UIImage *img = [manager.imageCache imageFromMemoryCacheForKey:key];
        if (img)
        {
            if (!(options & SDWebImageAvoidAutoSetImage))
            {
                if (self.isSetBgImg) /// 判断是设置成背景图片还是普通图片
                {
                    [self setBackgroundImage:img forState:UIControlStateNormal];
                }
                else
                {
                    [self setImage:img forState:UIControlStateNormal];
                }
            }
            
            return img;
        }
    }
    
    return nil;
}

- (void)sd_getCatcheDiskImageWithImageURL:(NSURL *)imgUrl options:(MPWebImageOptions)options finish:(void (^)(UIImage *image))finish
{
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
    NSString *key = [manager cacheKeyForURL:imgUrl];
    
    if (key && !(options & MPWebImageOption_UseNSURLCache) &&
        !(options & MPWebImageOption_RefreshImageCache))
    {
        dispatch_async([[self class] mp_setterQueue], ^{
            
            UIImage *img = [manager.imageCache imageFromDiskCacheForKey:key];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (img)
                {
                    if (!(options & MPWebImageOption_AvoidSetImage))
                    {
                        if (self.isSetBgImg) /// 判断是设置成背景图片还是普通图片
                        {
                            [self setBackgroundImage:img forState:UIControlStateNormal];
                        }
                        else
                        {
                            [self setImage:img forState:UIControlStateNormal];
                        }

                    }
                    
                    finish(img);
                }
                else
                {
                    finish(nil);
                }
            });
        });
    }
    else
    {
        finish(nil);
    }
    
}

- (void)sd_downImageWithImageURL:(NSURL *)imgUrl
                         options:(MPWebImageOptions)options
                        progress:(MPWebImageDownloaderProgressBlock)progressBlock
                         success:(nullable MPWebImageSuccessBlock)success
                            fail:(nullable MPWebImageFailBlock)fail
{
    /// 开始下载网络图片
    if (([imgUrl isKindOfClass:[NSURL class]]))
    {
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        
        __weak typeof(self) weakSelf = self;
        
        SDWebImageDownloaderProgressBlock _progress = nil;
        if (progressBlock)
        {
            _progress = ^(NSInteger receivedSize, NSInteger expectedSize)
            {
                progressBlock(receivedSize, expectedSize,imgUrl);
            };
        }
        
        id <SDWebImageOperation> operation = [manager downloadImageWithURL:imgUrl
                                                               options:(SDWebImageOptions)options
                                                              progress:_progress
                                                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL)
                                              {
                                                  /// 如果此时View已经释放，直接返回
                                                  if (!weakSelf)
                                                      return;
                                                  
                                                  mp_dispatch_main_sync_safe(^{
                                                      if (!weakSelf) return;
                                                      
                                                      if (finished)
                                                      {
                                                          if (image && (options & SDWebImageAvoidAutoSetImage) && success)
                                                          {
                                                              success(image,imageURL, [[self class] getMPImageCacheType:cacheType],MPWebImageStage_Finished);
                                                              return;
                                                          }
                                                          else if (image && !error)
                                                          {
                                                              /// 处理动画和图片校验
                                                              if ([weakSelf respondsToSelector:@selector(didFinishWithImage:)])
                                                              {
                                                                  [weakSelf performSelector:@selector(didFinishWithImage:) withObject:image];
                                                              }
                                                              else
                                                              {
                                                                  CATransition *transition = [CATransition animation];
                                                                  transition.duration = 0.2;
                                                                  transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
                                                                  transition.type = kCATransitionFade;
                                                                  [self.layer addAnimation:transition forKey:MPWebImageFadeAnimationKey];
                                                                  
                                                                  if (self.isSetBgImg) /// 判断是设置成背景图片还是普通图片
                                                                  {
                                                                      [self setBackgroundImage:image forState:UIControlStateNormal];
                                                                  }
                                                                  else
                                                                  {
                                                                      [self setImage:image forState:UIControlStateNormal];
                                                                  }
                                                              }
                                                              
                                                              if (success)
                                                              {
                                                                  success(image,imageURL, [[self class] getMPImageCacheType:cacheType],MPWebImageStage_Finished);
                                                              }
                                                              
                                                              return;
                                                          }
                                                          
                                                          if (error)
                                                          {
                                                              if ([weakSelf respondsToSelector:@selector(didFailWithError:)])
                                                              {
                                                                  [weakSelf performSelector:@selector(didFailWithError:) withObject:error];
                                                              }
                                                              
                                                              if (fail)
                                                              {
                                                                  fail(imageURL, [[self class] getMPImageCacheType:cacheType],MPWebImageStage_Finished,error);
                                                              }
                                                          }
                                                      }
                                                      else
                                                      {
                                                          if (options & SDWebImageProgressiveDownload)
                                                          {
                                                              if (image)
                                                              {
                                                                  if ([weakSelf respondsToSelector:@selector(noFinishWhitImage:)])
                                                                  {
                                                                      [weakSelf performSelector:@selector(noFinishWhitImage) withObject:image];
                                                                  }
                                                              }
                                                          }
                                                      }
                                                  });
                                              }];
        
        [self sd_setImageLoadOperation:operation forKey:SDWebImageLoadOperationKey];
    }
}

+ (MPWebImageFromType)getMPImageCacheType:(SDImageCacheType)cacheType
{
    MPWebImageFromType sdCacheState = [[[self dicSDImageCacheType] objectForKey:@(cacheType)] integerValue];
    
    return sdCacheState;
}

+ (NSDictionary *)dicSDImageCacheType
{
    return @{
             @(SDImageCacheTypeNone):@(MPWebImageCacheFromType_None),
             @(SDImageCacheTypeMemory):@(MPWebImageFromType_Memory),
             @(SDImageCacheTypeDisk):@(MPWebImageFromType_Disk)
             };
}

+ (void)sd_clearCatcheDisk:(void (^)())completion
{
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^
     {
         if (completion)
         {
             completion();
         }
     }];
}

+ (void)sd_clearCatcheMemory
{
    [[SDImageCache sharedImageCache] clearMemory];
}

#endif


@end
